package com.atguigu.gulimall.auth.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.service.RegisterService;
import com.atguigu.gulimall.auth.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @DESCRIPTION:
 * @author: zr
 * @DATE: 2022/12/31 11:34
 */
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 重定向携带数据  利用session原理 将数据放到session中 只要跳到下一个页面取出这个数据之后 session里面的数据就会删掉
     * // TODO 需要解决分布式下session问题
     *
     * @param registerVo
     * @param bindingResult
     * @param redirectAttributes 模拟重定向携带数据
     * @return
     */
    @Override
    public String register(RegisterVo registerVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            // 得到有错误的字段
            Map<String, String> errorMessage = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errorMessage);
            // Request method POST not supported
            // 用户注册->/regist [post] ====>转发 /reg.html (路径映射默认都是get方式访问的)
            // 校验出错 转发到注册页 重定向 避免表单重复提交  但是共享数据不能使用model
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 校验验证码是否正确 从redis种获取验证码
        String code = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if (StringUtils.hasText(code)) {
            // 对code进行分割
            String splitCode = code.split("_")[0];
            if (Objects.equals(splitCode, registerVo.getCode())) {
                //  删除验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
                // 远程调用服务 进行注册
                R register = memberFeignService.register(registerVo);
                if (register.getCode() == 0) {
                    // 注册成功 跳入登录页面
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    // 注册失败
                    Map<String, String> map = new HashMap<>(1);
                    // 获取错误响应消息
                    map.put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", map);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> map = new HashMap<>(1);
                map.put("code", "验证码不正确");
                redirectAttributes.addFlashAttribute("errors", map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> map = new HashMap<>(1);
            map.put("code", "验证码已过期");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }
}
